package com.krdz.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.xmlbeans.impl.util.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.krdz.bean.PersonBean;
import com.krdz.bean.QrBean;
import com.krdz.bean.QrCondition;
import com.krdz.service.QrService;
import com.krdz.util.BufferedImageLuminanceSource;
import com.krdz.util.QRGenUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
import net.glxn.qrgen.vcard.VCard;
import sun.misc.BASE64Decoder;
/**
 * 二维码管理控制器类
 * @author dinghao
 *
 * @date  2018年11月15日
 */
@Controller
@RequestMapping("qr")
public class QrController {
	@Resource
	private QrService qrService;
	
	//定义全局常量用于生成编码
	public static final int qr_count=1;
	//查询二维码信息
	@RequestMapping(value="/getQrInfo",produces="application/json;charset=UTF-8")
	@ResponseBody	
	public String getQrInfo(QrBean qr){		
		List<QrBean> li=qrService.findQrInfo(qr);
		String json= JSONObject.toJSONString(li);
		return json;	
	}
	//删除二维码信息
	@RequestMapping(value="/deleteQr",produces="application/json;charset=UTF-8")
	@ResponseBody	
	public String deleteQr(QrBean qr){
		if(qrService.deleteQr(qr)){
			return "success";
		}else{
			return "error";
		}
	}
	//扫描二维码得到信息
	@RequestMapping(value="/scanQrCode",produces="application/json;charset=UTF-8")
	@ResponseBody	
	public String scanQrCode(String path){
		
		String result=qrService.scanQrCode(path);
		JSONObject json=new JSONObject();
		json.put("data",result);
		json.put("count", 1);
		json.put("msg", "查询成功");
		json.put("code", 0);
		return json.toString();
	}
	
	//根据用户信息生成二维码，方式一：生成图片保存到本地文件
	@RequestMapping(value="/createUserQrCode",produces="application/json;charset=UTF-8")
	@ResponseBody	
	public String createUserQrCode(@RequestParam("newstr")String content,@RequestParam("fileName")String fileName) throws WriterException, IOException{
		String path=qrService.createUserQrCode(content,fileName);
		return path; 
	}
	//方式二：二维码生成流形式传递
	   @RequestMapping(value = "/getQ", method = { RequestMethod.POST, RequestMethod.GET })
	    public void getqcode(HttpServletResponse resp) throws IOException {
	        String result = "asdas";
	        if (result != null && !"".equals(result)) {
	            ServletOutputStream stream = null;
	            try {

	                int width = 200;//图片的宽度
	                int height = 200;//高度
	                stream = resp.getOutputStream();
	                QRCodeWriter writer = new QRCodeWriter();
	                BitMatrix m = writer.encode(result, BarcodeFormat.QR_CODE, height, width);
	                MatrixToImageWriter.writeToStream(m, "png", stream);
	            } catch (WriterException e) {
	                e.printStackTrace();
	            } finally {
	                if (stream != null) {
	                    stream.flush();
	                    stream.close();
	                }
	            }
	        }
	    }
	   //方式三：二维码转换base64加密传递
		@RequestMapping(value="/getQr",produces="application/json;charset=UTF-8")
		@ResponseBody	
		public String createUserQrCode(@RequestParam("qrType")Integer type,@RequestParam("content")String value) {
			BufferedImage qrImageBuffer;
			try {
				qrImageBuffer = QRGenUtils.createQRImageBuffer(value, 200, 200);
				ByteArrayOutputStream os=new ByteArrayOutputStream();
				ImageIO.write(qrImageBuffer, "png", os);
				Base64 base64 = new Base64();
				String base64Img = new String(base64.encode(os.toByteArray()));
				//查询当前数据库存储记录数
				int count=qrService.findQrCount();
				int code=10001;
				if(count==qr_count){
					code++;
				}
				if(count>qr_count){
					code++;
					code+=(count-qr_count);
				}
				
				//调用数据入写入接口把生成的二维码信息存入数据库
				QrBean qr=new QrBean();
				qr.setQrCode("T"+code);
				qr.setQrType(type);
				qr.setQrBase(base64Img);
			
				boolean flag=qrService.insertQr(qr);
				if(flag){
					System.out.println("写入成功！");
				}else{
					System.out.println("写入失败");
				}
				
				return base64Img;
			} catch (Exception e) {

				e.printStackTrace();
			}
			return "error";
		}
		
	//生成用户名片二维码
	@RequestMapping(value="/getQrVCard",produces="application/json;charset=UTF-8")
	@ResponseBody	
	public String CreateQrCodeVCard(PersonBean person){
		VCard vCard = new VCard();
        vCard.setName(person.getPersonName());
        vCard.setAddress(person.getPersonAddress());
        vCard.setCompany(person.getPersonCompany());
        vCard.setPhonenumber(person.getPersonPhonenumber());
        vCard.setTitle(person.getPersonTitle());
        vCard.setEmail(person.getPersonEmail());
        vCard.setWebsite(person.getPersonWebsite());
        ByteArrayOutputStream bout =QRCode.from(vCard)
                .withCharset("utf-8")
                .withSize(250, 250)
                .to(ImageType.PNG)
                .stream();
        Base64 base64 = new Base64();
        String base64Img = new String(base64.encode(bout.toByteArray()));
        if(base64Img!=""){
        	return base64Img;
        }
        return "error";
	}
	
	//读取二维码信息
	@RequestMapping(value="/readQrCode",produces="application/json;charset=UTF-8")
	@ResponseBody	
	public String readQrCode(String Basekey){
		BufferedImage bufImg=null;
		try {
			byte[] bytes =this.base64Stream(Basekey);
			InputStream ist =  new ByteArrayInputStream(bytes); 
			bufImg = ImageIO.read(ist);
			LuminanceSource source = new BufferedImageLuminanceSource(bufImg);  
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); 
			QRCodeReader reader = new QRCodeReader(); 
			Result result = null ; 		
			result = reader.decode(bitmap);
			System.out.println(result.getText());
			return result.getText();
			} catch (NotFoundException e) {
				e.printStackTrace();
			} catch (ChecksumException e) {
				e.printStackTrace();
			} catch (FormatException e) {
				e.printStackTrace();
			} catch (IOException e) {
			e.printStackTrace();
		}
		return "error";
}	
	//base64解码
	private byte[] base64Stream(String basekey) {
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] bytes = null;
		try {
			bytes = decoder.decodeBuffer(basekey);
			 for (int i = 0; i < bytes.length; ++i) {
				 if (bytes[i] < 0) {// 调整异常数据
					 bytes[i] += 256;
				 }
			 }	
		}catch(Exception e){		
	}
		return bytes;
}
	
	//获取二维码总记录数
	@RequestMapping(value="/getQrCount",produces="application/json;charset=UTF-8")
	@ResponseBody	
	public String getQrCount(){
		Integer count=qrService.findQrCount();
		
		return count.toString();
	}
	
	//获取二维码各类型记录数
	@RequestMapping(value="/getQrByType",produces="application/json;charset=UTF-8")
	@ResponseBody	
	public String getQrByType(){
		List<QrCondition> li=qrService.findQrTypeCount();
		String json= JSONObject.toJSONString(li);
		return json;
	}
}